package com.stud.framework.web.service;

import com.google.common.collect.Maps;
import com.stud.common.constant.CacheConstants;
import com.stud.common.constant.Constants;
import com.stud.common.constant.UserConstants;
import com.stud.common.core.domain.model.LoginUser;
import com.stud.common.core.redis.RedisCache;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.ServletUtils;
import com.stud.common.utils.StringUtils;
import com.stud.common.utils.ip.AddressUtils;
import com.stud.common.utils.ip.IpUtils;
import com.stud.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author Stud
 */
@Service
@Slf4j
public class TokenService {
    protected static final long MILLIS_SECOND = 1000;
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    private static final Long DAY = 604800000L;
    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;
    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;
    /**
     * 是否允许多段登录
     */
    @Value("${token.single}")
    private Boolean single;
    /**
     * 令牌有效期（默认30分钟）
     */
    @Value("${token.expireTime}")
    private int expireTime;
    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        try {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            LoginUser loginUser = redisCache.getCacheObject(userKey);

            if (Objects.isNull(loginUser)) {
                return null;
            }

            return loginUser;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public boolean delLoginUser(String token) {
        String userKey = getTokenKey(token);
        LoginUser loginUser = redisCache.getCacheObject(userKey);
        redisCache.deleteObject(userKey);

        String userName2UserKey = CacheConstants.USERNAME_2_USERKEY + loginUser.getUsername();

        Set<String> cacheSet = redisCache.getCacheSet(userName2UserKey);
        if (cacheSet.contains(userKey)) {
            redisCache.delCacheSetValue(userName2UserKey, userKey);
        }
        return true;
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        return createToken(loginUser, IdUtils.fastUUID());
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     */
    public String createToken(LoginUser loginUser, String token) {
        loginUser.setToken(token);
        setUserAgentDev(loginUser);
        refreshToken(loginUser);
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(Constants.LOGIN_USER_KEY, token);
        String authorization = createToken(claims);
        return authorization;
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     */
    public void verifyToken(LoginUser loginUser) {
        if (Objects.isNull(loginUser.getExpireTime())) {
            return;
        }
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());

        long realExpireTime;

        if (UserConstants.USER_TYPE_SSO.equals(loginUser.getUserType())) {
            //没有设置过期时间的SSO用户,永不过期
            if (Objects.isNull(loginUser.getUser().getExpireTime())) {
                realExpireTime = -1;
            } else {
                loginUser.setExpireTime(loginUser.getUser().getExpireTime().getTime());
                realExpireTime = loginUser.getExpireTime() - System.currentTimeMillis();
                if (realExpireTime < 0) {
                    throw new ServiceException("登录用户：" + loginUser.getUsername() + " 已过期");
                }
            }
        } else {
            //判断登录请求是否来自小程序端,如果是,设置token过期时间为 7 天  604800000 ms
            if (UserConstants.ISAPP.equals(loginUser.getIsApp())) {
                loginUser.setExpireTime(loginUser.getLoginTime() + DAY);
                realExpireTime = DAY;
            } else {
                loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
                realExpireTime = expireTime * MILLIS_MINUTE;
            }
        }

        String userName2UserKey = CacheConstants.USERNAME_2_USERKEY + loginUser.getUsername();
        String userKey = getTokenKey(loginUser.getToken());

        Set<String> userKeySet = redisCache.getCacheSet(userName2UserKey);

        if (!CollectionUtils.isEmpty(userKeySet)) {
            if (single || StringUtils.equals(UserConstants.USER_TYPE_SSO, loginUser.getUserType())) {
                redisCache.deleteObject(userKeySet);
                redisCache.deleteObject(userName2UserKey);
                userKeySet.clear();
            }
        }
        //这里的数据是递加的,借助set自动去重
        userKeySet.add(userKey);
        redisCache.setCacheSet(userName2UserKey, userKeySet);
        if (realExpireTime > 0) {
            redisCache.expire(userName2UserKey, realExpireTime, TimeUnit.MILLISECONDS);
            redisCache.setCacheObject(userKey, loginUser, realExpireTime, TimeUnit.MILLISECONDS);
        } else {
            redisCache.setCacheObject(userKey, loginUser);
        }

    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgentDev(LoginUser loginUser) {
        loginUser.setIpaddr("127.0.0.1");
        loginUser.setLoginLocation("内网IP");
        loginUser.setBrowser("Firefox 10");
        loginUser.setOs("Windows 10");
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 获取请求token
     *
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

}
